package cn.huimin.httpClient.entity;

import cn.huimin.httpClient.ex.URLEmptyException;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 */
public class HttpClientEntity {

    //默认端口号
    private Long port = 80L;

    private String url = "";

    private TreeMap<String, Object> params = new TreeMap<String, Object>();

    private Map<String, String> header = new HashMap<String, String>();

    /**
     * 获取请求URL
     * @return
     * @throws Exception
     */
    public StringBuffer getRequestUrl() throws URLEmptyException{
        StringBuffer requestUrl = new StringBuffer();
        if(StringUtils.isNotBlank(url)){
            if(port!=80L){
                requestUrl.append(url).append(":").append(port);
            }else{
                requestUrl.append(url);
            }
        }else{
            throw new URLEmptyException("request url is empty!");
        }
        return requestUrl;
    }


    /**
     * 获取post请求的URL
     * @return
     * @throws Exception
     */
    public StringBuffer getPostUrl() throws URLEmptyException {

        return getRequestUrl();
    }

    /**
     * 获取put请求的URL
     * @return
     * @throws Exception
     */
    public StringBuffer getPutUrl() throws URLEmptyException {

        return getRequestUrl();
    }

    /**
     * 获取get请求的URL
     * @return
     * @throws Exception
     */
    public StringBuffer getGetUrl() throws URLEmptyException {
        StringBuffer requestUrl = getRequestUrl();
        if (params.size() > 0) {
            requestUrl.append("?");
        }
        int i = 0;
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() instanceof String) {
                if (i != 0) {
                    requestUrl.append("&");
                }
                requestUrl.append(entry.getKey()).append("=").append(
                        entry.getValue().toString());
                i++;
            }
        }
        return requestUrl;
    }

    public void clearParmas() {
        params.clear();
    }

    public void addParam(String name, Object value) {
        params.put(name, value);
    }

    public void addHeader(String name, String value) {
        header.put(name, value);
    }

    public void setPort(Long port) {
        this.port = port;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public TreeMap<String, Object> getParams() {
        return params;
    }

    public Map<String, String> getHeader() {
        return header;
    }

}
